package com.blog.cmrpersonalblog.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.blog.cmrpersonalblog.common.Result;
import com.blog.cmrpersonalblog.dto.comment.request.CommentBatchOperationRequest;
import com.blog.cmrpersonalblog.dto.comment.request.CommentQueryRequest;
import com.blog.cmrpersonalblog.dto.comment.request.LatestCommentsRequest;
import com.blog.cmrpersonalblog.dto.comment.request.PopularCommentsRequest;
import com.blog.cmrpersonalblog.dto.comment.responst.CommentManagementResponse;
import com.blog.cmrpersonalblog.dto.sensitiveword.requset.SensitiveWordCheckResult;
import com.blog.cmrpersonalblog.entity.Comment;
import com.blog.cmrpersonalblog.service.CommentManagementService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

/**
 * 评论管理控制器
 * 提供评论的管理功能，包括列表查询、审核、批量操作、敏感词过滤等
 */
@Slf4j
@RestController
@RequestMapping("/admin/comments")
@CrossOrigin(origins = "*", maxAge = 3600)
@SaCheckRole("admin")
@Validated
public class CommentManagementController {

   @Resource
    private CommentManagementService commentManagementService;

    /**
     * 分页查询评论列表
     */
    @GetMapping("/list")
    public Result<IPage<CommentManagementResponse>> getCommentList(CommentQueryRequest queryRequest) {
        log.info("管理员查询评论列表: {}", queryRequest);
        try {
            IPage<CommentManagementResponse> pageResult = commentManagementService.getCommentList(queryRequest);
            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("查询评论列表失败", e);
            return Result.error("查询评论列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取评论详情
     */
    @GetMapping("/{commentId}")
    public Result<CommentManagementResponse> getCommentDetail(@PathVariable @NotNull Long commentId) {
        log.info("管理员查看评论详情: commentId={}", commentId);
        try {
            CommentManagementResponse detail = commentManagementService.getCommentDetail(commentId);
            if (detail == null) {
                return Result.error("评论不存在");
            }
            return Result.success(detail);
        } catch (Exception e) {
            log.error("获取评论详情失败", e);
            return Result.error("获取评论详情失败：" + e.getMessage());
        }
    }

    /**
     * 获取评论树形结构
     */
    @GetMapping("/tree")
    public Result<List<CommentManagementResponse>> getCommentTree(
            @RequestParam @NotNull Long articleId,
            @RequestParam(required = false) Long rootId) {
        log.info("管理员查看评论树: articleId={}, rootId={}", articleId, rootId);
        try {
            List<CommentManagementResponse> commentTree = commentManagementService.getCommentTree(articleId, rootId);
            return Result.success(commentTree);
        } catch (Exception e) {
            log.error("获取评论树失败", e);
            return Result.error("获取评论树失败：" + e.getMessage());
        }
    }

    /**
     * 创建评论（自动处理敏感词）
     */
    @PostMapping("/create")
    @SaCheckLogin  // 登录用户即可创建评论
    public Result<Void> createComment(@RequestBody @Valid Comment comment) {
        Long userId = StpUtil.getLoginIdAsLong();
        comment.setUserId(userId);
        log.info("用户创建评论: userId={}, articleId={}", userId, comment.getArticleId());

        try {
            boolean success = commentManagementService.createComment(comment);
            if (success) {
                return Result.success("评论发布成功");
            } else {
                return Result.error("评论发布失败");
            }
        } catch (Exception e) {
            log.error("创建评论失败", e);
            return Result.error("评论发布失败：" + e.getMessage());
        }
    }

    /**
     * 批量操作评论
     */
    @PostMapping("/batch")
    public Result<Map<String, Object>> batchOperateComments(@RequestBody @Valid CommentBatchOperationRequest batchRequest) {
        Long operatorId = StpUtil.getLoginIdAsLong();
        log.info("管理员批量操作评论: request={}, operatorId={}", batchRequest, operatorId);
        
        try {
            Map<String, Object> result = commentManagementService.batchOperateComments(batchRequest, operatorId);
            return Result.success("批量操作完成", result);
        } catch (Exception e) {
            log.error("批量操作评论失败", e);
            return Result.error("批量操作失败：" + e.getMessage());
        }
    }

    /**
     * 删除评论
     */
    @DeleteMapping("/{commentId}")
    public Result<Void> deleteComment(@PathVariable @NotNull Long commentId) {
        Long operatorId = StpUtil.getLoginIdAsLong();
        log.info("管理员删除评论: commentId={}, operatorId={}", commentId, operatorId);
        
        try {
            boolean success = commentManagementService.deleteComment(commentId, operatorId);
            if (success) {
                return Result.success("评论删除成功");
            } else {
                return Result.error("评论删除失败");
            }
        } catch (Exception e) {
            log.error("删除评论失败", e);
            return Result.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 恢复评论
     */
    @PostMapping("/{commentId}/restore")
    public Result<Void> restoreComment(@PathVariable @NotNull Long commentId) {
        Long operatorId = StpUtil.getLoginIdAsLong();
        log.info("管理员恢复评论: commentId={}, operatorId={}", commentId, operatorId);
        
        try {
            boolean success = commentManagementService.restoreComment(commentId, operatorId);
            if (success) {
                return Result.success("评论恢复成功");
            } else {
                return Result.error("评论恢复失败");
            }
        } catch (Exception e) {
            log.error("恢复评论失败", e);
            return Result.error("恢复失败：" + e.getMessage());
        }
    }

    /**
     * 硬删除评论（管理端专用，谨慎使用）
     */
    @DeleteMapping("/{commentId}/hard-delete")
    public Result<Void> hardDeleteComment(@PathVariable @NotNull Long commentId) {
        Long operatorId = StpUtil.getLoginIdAsLong();
        log.info("管理员硬删除评论: commentId={}, operatorId={}", commentId, operatorId);
        
        try {
            boolean success = commentManagementService.hardDeleteComment(commentId, operatorId);
            if (success) {
                return Result.success("评论永久删除成功");
            } else {
                return Result.error("评论永久删除失败");
            }
        } catch (Exception e) {
            log.error("硬删除评论失败", e);
            return Result.error("永久删除失败：" + e.getMessage());
        }
    }

    /**
     * 标记敏感评论
     */
    @PostMapping("/{commentId}/mark-sensitive")
    public Result<Void> markSensitive(@PathVariable @NotNull Long commentId, 
                                     @RequestParam String sensitiveType) {
        Long operatorId = StpUtil.getLoginIdAsLong();
        log.info("管理员标记敏感评论: commentId={}, type={}, operatorId={}", commentId, sensitiveType, operatorId);
        
        try {
            boolean success = commentManagementService.markSensitive(commentId, sensitiveType, operatorId);
            if (success) {
                return Result.success("标记敏感成功");
            } else {
                return Result.error("标记敏感失败");
            }
        } catch (Exception e) {
            log.error("标记敏感评论失败", e);
            return Result.error("标记失败：" + e.getMessage());
        }
    }

    /**
     * 取消敏感标记
     */
    @PostMapping("/{commentId}/unmark-sensitive")
    public Result<Void> unmarkSensitive(@PathVariable @NotNull Long commentId) {
        Long operatorId = StpUtil.getLoginIdAsLong();
        log.info("管理员取消敏感标记: commentId={}, operatorId={}", commentId, operatorId);
        
        try {
            boolean success = commentManagementService.unmarkSensitive(commentId, operatorId);
            if (success) {
                return Result.success("取消敏感标记成功");
            } else {
                return Result.error("取消敏感标记失败");
            }
        } catch (Exception e) {
            log.error("取消敏感标记失败", e);
            return Result.error("取消标记失败：" + e.getMessage());
        }
    }

    /**
     * 检测敏感词
     */
    @PostMapping("/check-sensitive")
    @SaCheckLogin  // 降低权限要求，登录用户即可使用
    public Result<SensitiveWordCheckResult> checkSensitiveWords(@RequestBody String content) {
        log.info("检测敏感词: contentLength={}", content.length());
        try {
            SensitiveWordCheckResult result = commentManagementService.checkCommentSensitiveWords(content);
            return Result.success(result);
        } catch (Exception e) {
            log.error("检测敏感词失败", e);
            return Result.error("检测失败：" + e.getMessage());
        }
    }

    /**
     * 获取评论统计信息
     */
    @GetMapping("/statistics")
    public Result<Map<String, Object>> getCommentStatistics() {
        log.info("管理员查看评论统计信息");
        try {
            Map<String, Object> statistics = commentManagementService.getCommentStatistics();
            return Result.success(statistics);
        } catch (Exception e) {
            log.error("获取评论统计信息失败", e);
            return Result.error("获取统计信息失败：" + e.getMessage());
        }
    }



    /**
     * 获取敏感评论数量
     */
    @GetMapping("/sensitive-count")
    public Result<Long> getSensitiveCommentCount() {
        try {
            Long count = commentManagementService.getSensitiveCommentCount();
            return Result.success(count);
        } catch (Exception e) {
            log.error("获取敏感评论数量失败", e);
            return Result.error("获取数量失败：" + e.getMessage());
        }
    }

    /**
     * 获取评论状态分布
     */
    @GetMapping("/status-distribution")
    public Result<Map<String, Long>> getCommentStatusDistribution() {
        log.info("管理员查看评论状态分布");
        try {
            Map<String, Long> distribution = commentManagementService.getCommentStatusDistribution();
            return Result.success(distribution);
        } catch (Exception e) {
            log.error("获取评论状态分布失败", e);
            return Result.error("获取状态分布失败：" + e.getMessage());
        }
    }

    /**
     * 获取敏感词类型分布
     */
    @GetMapping("/sensitive-type-distribution")
    public Result<Map<String, Long>> getSensitiveTypeDistribution() {
        log.info("管理员查看敏感词类型分布");
        try {
            Map<String, Long> distribution = commentManagementService.getSensitiveTypeDistribution();
            return Result.success(distribution);
        } catch (Exception e) {
            log.error("获取敏感词类型分布失败", e);
            return Result.error("获取类型分布失败：" + e.getMessage());
        }
    }

    /**
     * 分页获取最新评论列表
     */
    @GetMapping("/latest")
    public Result<IPage<CommentManagementResponse>> getLatestComments(LatestCommentsRequest request) {
        log.info("管理员查看最新评论: {}", request);
        try {
            IPage<CommentManagementResponse> pageResult = commentManagementService.getLatestComments(request);
            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("获取最新评论失败", e);
            return Result.error("获取最新评论失败：" + e.getMessage());
        }
    }

    /**
     * 分页获取热门评论列表
     */
    @GetMapping("/popular")
    public Result<IPage<CommentManagementResponse>> getPopularComments(PopularCommentsRequest request) {
        log.info("管理员查看热门评论: {}", request);
        try {
            IPage<CommentManagementResponse> pageResult = commentManagementService.getPopularComments(request);
            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("获取热门评论失败", e);
            return Result.error("获取热门评论失败：" + e.getMessage());
        }
    }

    /**
     * 搜索评论
     */
    @GetMapping("/search")
    public Result<IPage<CommentManagementResponse>> searchComments(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "1") Long current,
            @RequestParam(defaultValue = "10") Long size) {
        log.info("管理员搜索评论: keyword={}, current={}, size={}", keyword, current, size);
        try {
            IPage<CommentManagementResponse> pageResult = commentManagementService.searchComments(keyword, current, size);
            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("搜索评论失败", e);
            return Result.error("搜索失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户评论列表
     */
    @GetMapping("/user/{userId}")
    public Result<IPage<CommentManagementResponse>> getUserComments(
            @PathVariable @NotNull Long userId,
            @RequestParam(defaultValue = "1") Long current,
            @RequestParam(defaultValue = "10") Long size) {
        log.info("管理员查看用户评论: userId={}, current={}, size={}", userId, current, size);
        try {
            IPage<CommentManagementResponse> pageResult = commentManagementService.getUserComments(userId, current, size);
            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("获取用户评论失败", e);
            return Result.error("获取用户评论失败：" + e.getMessage());
        }
    }

    /**
     * 获取文章评论列表
     */
    @GetMapping("/article/{articleId}")
    public Result<IPage<CommentManagementResponse>> getArticleComments(
            @PathVariable @NotNull Long articleId,
            @RequestParam(defaultValue = "1") Long current,
            @RequestParam(defaultValue = "10") Long size) {
        log.info("管理员查看文章评论: articleId={}, current={}, size={}", articleId, current, size);
        try {
            IPage<CommentManagementResponse> pageResult = commentManagementService.getArticleComments(articleId, current, size);
            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("获取文章评论失败", e);
            return Result.error("获取文章评论失败：" + e.getMessage());
        }
    }

    /**
     * 根据IP地址获取评论列表
     */
    @GetMapping("/ip/{ipAddress}")
    public Result<IPage<CommentManagementResponse>> getCommentsByIpAddress(
            @PathVariable String ipAddress,
            @RequestParam(defaultValue = "1") Long current,
            @RequestParam(defaultValue = "10") Long size) {
        log.info("管理员查看IP评论: ipAddress={}, current={}, size={}", ipAddress, current, size);
        try {
            IPage<CommentManagementResponse> pageResult = commentManagementService.getCommentsByIpAddress(ipAddress, current, size);
            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("获取IP评论失败", e);
            return Result.error("获取IP评论失败：" + e.getMessage());
        }
    }

    /**
     * 重新计算评论统计数据
     */
    @PostMapping("/{commentId}/recalculate-stats")
    public Result<Void> recalculateCommentStats(@PathVariable @NotNull Long commentId) {
        Long operatorId = StpUtil.getLoginIdAsLong();
        log.info("管理员重新计算评论统计: commentId={}, operatorId={}", commentId, operatorId);
        
        try {
            boolean success = commentManagementService.recalculateCommentStats(commentId);
            if (success) {
                return Result.success("统计数据重新计算成功");
            } else {
                return Result.error("统计数据重新计算失败");
            }
        } catch (Exception e) {
            log.error("重新计算评论统计失败", e);
            return Result.error("重新计算失败：" + e.getMessage());
        }
    }
}
